package com.example.controller;

import com.example.pojo.Result;
import com.example.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class UploadController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

//    @PostMapping("/upload")
//    public Result upload(String name, String age, MultipartFile file) {
//        log.info("接收，年龄{}，名{}，文件{}", age, name, file);
//        // 处理接受的文件
//        String fileName = file.getOriginalFilename();
//
//        // 重命名文件
//        String suffix = fileName.substring(fileName.lastIndexOf("."));//获取文件后缀
//        String newFileName= UUID.randomUUID().toString()+suffix;
//        // 保存文件到本地
//        try {
//            file.transferTo(new File("F:/upload/" + newFileName));
//            //transferTO方法将文件保存到指定目录下
//        } catch (IOException e) {
//            e.printStackTrace();
//            return Result.error("上传失败");
//        }
//        return Result.success("上传成功");
//    }

    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        log.info("接收文件{}", file.getOriginalFilename());
        String url;
        try {
            url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.success(url);
    }
}
